package com.feshfans.bridge;

import com.feshfans.controller.special.MessageController;
import com.feshfans.controller.RegisteredController;
import com.feshfans.controller.StageManager;
import javafx.application.Platform;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.packet.Message;
import org.jxmpp.jid.EntityBareJid;

import java.util.HashMap;
import java.util.Map;

public class MessageBridge extends AbstractBridge {

    private static final MessageBridge MESSAGE_NOTIFY = new MessageBridge();

    // 因为用户同时打开的 聊天窗口会有多个，所以此处维护每一个打开的聊天窗口
    private Map<String, MessageController> map = new HashMap<>();
    private MessageBridge(){}


    public static MessageBridge getInstance(){
        return MESSAGE_NOTIFY;
    }


    @Override
    public synchronized void register(RegisteredController controller) {
        synchronized (MESSAGE_NOTIFY){
            MessageController messageController = (MessageController)controller;
            map.put(messageController.getJid(),messageController);
        }
    }

    /**
     * 当某一个 "聊天窗口" 关闭时，应去掉注册
     * @param controller
     */
    @Override
    public synchronized void unregister(RegisteredController controller) {
        synchronized (MESSAGE_NOTIFY){
            MessageController messageController = (MessageController)controller;
            map.remove(messageController.getJid());
        }
    }

    public synchronized void newIncomingMessage(EntityBareJid from, Message message, Chat chat){

        // 其它线程调用 FX 线程时，必须使用 Platform.runLater
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                // 如果不包含，说明窗口未打开
                if(!map.containsKey(from.toString())){
                    // 调用此名，会打开 MessageController,从而初始化 MessageController,执行 initialize()-> register()
                    // 所以，执行下面这一句，就将 controller 注册到了 Bridge
                    StageManager.openOrGetMessageStage(from);
                }
                // 获取注册的 Controller
                MessageController messageController = map.get(from.toString());
                // 处理收到的消息
                messageController.newIncomingMessage(from,message.getBody());
            }
        });

    }
}
